package tweeks.common.interceptor;

import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import tweeks.common.domain.UUIDEntity;

@Intercepts({@Signature(type=StatementHandler.class, method="parameterize", args={Statement.class})})
public class UUIDParameterizer implements Interceptor {
	private StatementHandler handler;

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		handler = (StatementHandler) invocation.getTarget();
		if (handler.getBoundSql().getSql().toLowerCase().startsWith("insert")) {
			Object obj = handler.getParameterHandler().getParameterObject();
			
			if (obj instanceof UUIDEntity) {
				Class<?> clazz = Class.forName("tweeks.common.domain.UUIDEntity");
				Object val = clazz.getMethod("getId", null).invoke(obj, null);
				if (((String) val) == null || "".equals((String) val)) {
					clazz.getMethod("generateValue", null).invoke(obj, null);
				}
			}
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		
	}

}
